package com.concorrency.learn.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.concorrency.learn.model.Money;
import com.concorrency.learn.model.Student;
import com.concorrency.learn.vo.AAA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by corey on 2018/9/8.
 */
@Service
public class PolymerizationService {
    @Autowired
    private UserService userService;
    @Autowired
    private MoneyService moneyService;

    /**
     * 普通实现
     * @param id
     * @return
     */
    public AAA getAaa(int id){
        long beting = System.currentTimeMillis();
        Student student = userService.getUserInfo(id);
        Money money = moneyService.getMoney(id);
        AAA aaa = new AAA();
        aaa.setName(student.getName());
        aaa.setAge(student.getAge());
        aaa.setBalabce(money.getBalabce());
        System.out.println("执行任务总共耗时："+(System.currentTimeMillis()-beting)+"毫秒");
        return aaa;
    }

    /**
     * 基于并发实现
     * @param id
     * @return
     */
    public AAA getAaaByConcorrent(int id) {
        long beting = System.currentTimeMillis();
        Callable<Student> getUserInfo = new Callable<Student>() {
            @Override
            public Student call() throws Exception {
                Student student = userService.getUserInfo(id);

                return student;
            }
        };
        Callable<Money> getMoney = new Callable<Money>() {
            @Override
            public Money call() throws Exception {
                Money money = moneyService.getMoney(id);
                return money;
            }
        };
        FutureTask<Student> studentTask = new FutureTask<Student>(getUserInfo);
        FutureTask<Money> moneyTask = new FutureTask<Money>(getMoney);
        new Thread(studentTask).start();
        new Thread(moneyTask).start();
        AAA aaa = new AAA();
        Student student = null;
        try {
            student = studentTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Money money = null;
        try {
            money = moneyTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        aaa.setName(student.getName());
        aaa.setAge(student.getAge());
        aaa.setBalabce(money.getBalabce());
        System.out.println("执行任务总共耗时："+(System.currentTimeMillis()-beting)+"毫秒");
        return aaa;

    }

}
